import 'package:flutter/foundation.dart';

typedef NotificationUsingBlock = Function(dynamic object);

class NotificationCenter {
  // 工厂模式
  factory NotificationCenter() => _getInstance();

  static NotificationCenter get instance => _getInstance();
  static NotificationCenter? _instance;

  NotificationCenter._internal();

  static NotificationCenter _getInstance() {
    if (_instance == null) {
      _instance = new NotificationCenter._internal();
    }
    return _instance!;
  }

  /// 存储所有的通知回调
  Map<String, List<NotificationUsingBlock>> _notificationBlock = Map<String, List<NotificationUsingBlock>>();

  /// 添加通知
  /// name：通知名称
  /// using：通知内容回调
  addNotification(String name, NotificationUsingBlock usingBlock) {
    final List<NotificationUsingBlock> _list = [];
    if (_notificationBlock.containsKey(name)) {
      _list.addAll(_notificationBlock[name]!);
    }
    _list.add(usingBlock);
    _notificationBlock[name] = _list;
    debugPrint('---😆😆addNotification,_notificationBlock: ${_notificationBlock}😆😆---');
  }

  /// 发送通知
  /// name：通知名称
  /// object：通知内容
  postNotification(String name, dynamic object) {
    if (_notificationBlock.containsKey(name)) {
      for (var block in _notificationBlock[name]!) {
        if (block != null) block(object);
      }
    }
  }

  /// 删除指定通知
  /// name：通知名称
  removeNotification(String name) {
    if (_notificationBlock.containsKey(name)) {
      var list = _notificationBlock[name];
      if (list!.length == 1) {
        _notificationBlock.remove(name);
      } else {
        list.removeLast();
        _notificationBlock[name] = list;
      }
    }
    debugPrint('---😆😆removeNotification,_notificationBlock: ${_notificationBlock}😆😆---');
  }

  /// 删除所有通知
  removeAllNotification() {
    _notificationBlock.clear();
  }
}
